<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            多码合批
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">扫描条码</div>
                    <input type="text" class="aui-input" placeholder="请扫描条码" style="width: 80%;" id="tm" onclick="getIdSelector();" onfocus="focusFn(this)">
                    <i class="aui-input-addon aui-iconfont aui-icon-scan " style="font-size: 1.6rem" onclick="toScanner();"></i>
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">蓝牙设备</div>
                    <select id="bluetooth">
                    </select>
                </div>
            </li>
        </ul>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info aui-btn-block" onclick="bluetoothConnect()">蓝牙连接</div>
        <div style="width:100%;margin-top:2%;"></div>
        <div class="aui-btn aui-btn-info" style="width:45%;margin-left:4%;" id="checkno" onclick="print()">合批打印</div>
        <div class="aui-btn aui-btn-info" style="width:45%;margin-left:2%;" id="returnGoodsbtn" onclick="deleteRows()">删除</div>

        <div style="width:100%;margin-top:2%;"></div>
        <div
            style="background-color:white; width: 100%;margin-top:2%;white-space: nowrap;overflow-x: auto;-webkit-overflow-scrolling:touch;">

            <table class="table" style='width:1000px;' id="table1">
                <tbody style="display:block">
                    <tr
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 15px;font-weight: bold;">
                        <td algin='center' style="width:50px;"></td>
                        <td algin='center' style="width:200px;">箱号</td>
                        <td algin='center' style="width:150px;;">物料号</td>
                        <td algin='center' style="width:150px;">物料名称</td>
                        <td algin='center' style="width:150px;">批次号</td>
                        <td algin='center' style="width:100px;">数量</td>
                        <td algin='center' style="width:100px;display:none">tm</td>
                    </tr>
                </tbody>
            </table>
            <table class="table" style='width:1000px;' id="table">
                <tbody id="tbodyHtml" style="display: block;height: 700px;overflow-y: scroll;">
                   <!-- <tr style='text-align: center;color: black;font-size: 16px;background-color: #F5F5F5;'>";
                    <td style='width:50px;' algin='center'><input name='sub' type='checkbox' /></td>";
                    <td style='width:200px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 200px;' algin='center' name='boxnum' >" + boxnum + "</td>
                    <td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='mrlCode'>" + mrlCode + "</td>
                     <td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='mrlName'>" + mrlName + "</td>
                    <td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='lotCode'>" + lotCode + "</td>
                    <td style='width:100px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 100px;' algin='center' name='qty'>" + qty + "</td>
                    </tr> -->
                </tbody>

            </table>
        </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">
    var scanRule = ""; //条码解析规则
    var boxnumSave = [];
    //初始化查询仓库下拉框
    apiready = function() {

        $("#tm").focus();
        // //查询打印机下拉框
        // selectPrintName();

        //查询条码解析规则
        initScanRule();

        //获取蓝牙列表
        getBluetoothCombox();
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        $("#" + el.id).select();
    }

    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                appVersion: api.appVersion,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    //查询蓝牙设备
    function getBluetoothCombox() {
        var modulePrinterCpclDJG = api.require('modulePrinterCpclDJG');
        modulePrinterCpclDJG.searchBluetooth({}, function(ret, err) {
            if (ret) {
                if (ret.code == "S") {
                    var list = ret.list;
                    var html = "<option value=''>--请选择--</option>";
                    for (var i = 0; i < list.length; i++) {
                        html += "<option value='" + list[i].code + "'>" + list[i].name + "</option>";
                    }
                    $api.html($api.byId("bluetooth"), html);

                    //取缓存中蓝牙设备打印机
                    var bluetooth = localStorage.getItem('bluetooth');
                    if (bluetooth != null && bluetooth != undefined && bluetooth != "") {
                        $("#bluetooth").val(bluetooth);
                    }

                } else {
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //蓝牙连接
    function bluetoothConnect() {
        var address = $("#bluetooth").val();
        if (address == null || address == "" || address == undefined) {
            api.toast({
                msg: "请选择蓝牙"
            });
            return;
        }
        // console.log(address);
        // api.showProgress({
        //     title: '连接中...',
        // });
        var modulePrinterCpclDJG = api.require('modulePrinterCpclDJG');
        modulePrinterCpclDJG.connectBluetooth({
            address: address,
        }, function(ret, err) {
            if (ret) {
                // api.hideProgress();
                if (ret.code == "S") {
                    api.toast({
                        msg: ret.message
                    });
                } else {
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    //打印
    function print() {
        var address = $("#bluetooth").val();
        if (address == null || address == "" || address == undefined) {
            api.toast({
                msg: "请选择蓝牙！"
            });
            return;
        }

        localStorage.setItem('bluetooth', address);

        if(boxnumSave.length <= 1){
            api.toast({
                msg: "请至少扫描2个箱码后进行合批！"
            });
            return;
        }

        var un = localStorage.getItem("un");
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getBatchSave";
        var data = {
            values: {
                boxnumSave: boxnumSave.toString(), //箱号
                appVersion: api.appVersion,
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {

                    //返回json数据
                    var json = myobj.json;

                    
                    boxnumSave = [];
                    //清空表格数据
                    $api.html($api.byId("tbodyHtml"), "");

                    //调用PDA打印
                    printPDA(json, address);


                } else {

                    $("#tm").val("");
                    $("#tm").select();
                    // api.toast({
                    //     msg: myobj.message,
                    //     duration: 3000
                    // });
                    alert(myobj.message);
                }
            } else {

                $("#tm").val("");
                alert(JSON.stringify(err));
            }
        });
    }

    //打印
    function printPDA(json, address) {
        var modulePrinterCpclDJG = api.require('modulePrinterCpclDJG');
        modulePrinterCpclDJG.printTemplateFourLineFourBySixQR({
            json: json, //打印数据JSON
            address: address //蓝牙地址
        }, function(ret, err) {
            if (ret) {

                if (ret.code == "S") {
                    api.toast({
                        msg: "打印成功"
                    });

                    $("#tm").focus();
                    
                } else {

                    $("#tm").val("");
                    api.toast({
                        msg: ret.message
                    });
                }
            } else {
                $("#tm").val("");
                alert(JSON.stringify(err));
            }
        });
    }

    //扫描发货单号和箱号
    function toScanner() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function(ret, err) {

            //条码解析
            tmSplit(ret);

        });
    }

    //条码监听回车事件
    $("#tm").on('keypress', function(e) {
        var keycode = e.keyCode;
        var tm = $(this).val();
        if (keycode == '13') {
            $("#tm").blur();
            //条码解析
            tmSplit(tm);
        }
    });

    //扫描之后条码解析
    function tmSplit(sm) {
        $("#tm").val(sm);
        //直接解析
        if (scanRule == "old") {

            //本地解析
            localAnalyze(sm);

        } else {

            //后台解析
            postAnalyze(sm);
        }
    }

    //本地解析
    function localAnalyze(sm) {
        var arr = sm.split(",");
        $("#boxnum").val(arr[9]);
        $("#qty").val(arr[2]);
        $("#supplierCode").val(arr[0]);
        $("#mrlCode").val(arr[1]);
        $("#lotCode").val(arr[3]);
        $("#kanban").val(arr[5]);
        $("#purchaseCode").val(arr[6]);
        $("#prodDate").val(arr[7]);
        $("#customer").val(arr[8]);
        $("#tmID").val(arr[4]);
        $("#packageQty").focus();
    }

    //后台解析条码
    function postAnalyze(sm) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getBatchSelectBox";
        var data = {
            values: {
                tm: sm, //条码
                appVersion: api.appVersion,
                un: un
            }

            
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 30,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    var str = "";
                    var boxnum = myobj.boxnum;
                    var mrlCode = myobj.mrlCode;
                    var mrlName = myobj.mrlName;
                    var lotCode = myobj.lotCode;
                    var qty = myobj.qty;
                    var tm = myobj.tm;

                    if (boxnumSave.includes(boxnum)) {
                        $("#tm").val("");
                        $("#tm").select();
                        api.toast({
                            msg: '箱号【' + boxnum + '】在列表中已存在!',
                            duration: 3000
                        });
                    } else {
                        str += "<tr style='text-align: center;color: black;font-size: 16px;background-color: #F5F5F5;'>";
                        str += "<td style='width:50px;' algin='center'><input name='sub' type='checkbox' /></td>";
                        str += "<td style='width:200px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 200px;' algin='center' name='boxnum' >" + boxnum + "</td>";
                        str += "<td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='mrlCode'>" + mrlCode + "</td>";
                        str += "<td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='mrlName'>" + mrlName + "</td>";
                        str += "<td style='width:150px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 150px;' algin='center' name='lotCode'>" + lotCode + "</td>";
                        str += "<td style='width:100px;white-space: normal;word-wrap: break-word;word-break: break-all;max-width: 100px;' algin='center' name='qty'>" + qty + "</td>";
                        str += "<td style='display:none' algin='center' name='tm'>" + tm + "</td>";
                        str += "</tr>";
                        
                        $("#tbodyHtml").append(str);

                        boxnumSave.push(boxnum);
                    }


                    $("#tm").val("");
                    $("#tm").select();
                } else if (myobj.code == '1') {

                    $("#tm").val("");
                    $("#tm").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    function deleteRows(){
        // 获取所有的checkbox
        var checkboxes = document.querySelectorAll('#tbodyHtml input[type="checkbox"]');
        
        // 遍历checkboxes
        checkboxes.forEach(function(checkbox) {
            if (checkbox.checked) {
                // 如果checkbox被选中，则删除其祖先<tr>元素
                checkbox.closest('tr').remove();
            }
        });
        
        var remainingBoxNums = document.querySelectorAll('#tbodyHtml [name="boxnum"]');

        boxnumSave = [];
        remainingBoxNums.forEach(function(boxNumElement) {
            // 收集剩余的boxnum值
            boxnumSave.push(boxNumElement.textContent || boxNumElement.innerText);
        });
        //console.log(boxnumSave)
    }

    function focusFn(ele){
        $api.attr(ele,'readonly', 'readonly');
        setTimeout(() => {
            $api.removeAttr(ele,'readonly');
        }, 200);
    };
    //返回按钮
    function closeWin() {
        api.closeWin({});
    }
</script>

</html>
